/*
 * Copyright (c) 2012 Acorn International.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http:www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or  implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

YAHOO.namespace("pingmob");
YAHOO.namespace("pingmob.container");

YAHOO.util.Event.onDOMReady(function () {
    YAHOO.pingmob.orderEdit = function () {

        // Put a LogReader on your page
        //this.myLogReader = new YAHOO.widget.LogReader();

        var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event;

        var returnUserList = function (p_oEvent) {
            window.location.href = "/ozing/users/cards";
        };

        var refreshUserCardsEdit = function (p_oEvent) {
            window.location.href = "/admin/ozing/user/cards?id="+Dom.get("id").value;
        };

        var updateUser = function (p_oEvent) {
            //document.forms["userForm"].submit();
        };

        // Define various event handlers for Dialog
        var handleAddGiftCardSubmit = function () {
            var username = Dom.get("username").value;
            var  gift_card_par_value = Dom.get("gift_card_par_value").value;
            var  cardExpirationDate = Dom.get("cardExpirationDate").value;
            if (gift_card_par_value == "" || cardExpirationDate == "") {
                alert("请输入赠卡的面额和过期日期");
                return false;
            }
            if (gift_card_par_value > 500) {
                alert("赠送的卡面值不能超过500");
                return false;
            }
            YAHOO.util.Connect.asyncRequest(
                'POST',
                '/admin/ozing/user/gift/card',
                {
                    success: function (o) {
                        if (o.responseText == "true") {
                            alert("赠卡成功");
                            window.location.href = "/admin/ozing/user/cards?id=" + Dom.get("id").value;
                        }
                    },
                    failure: function (o) {
                        alert(o.statusText);
                    },
                    scope: this
                }, "username=" + username + "&gift_card_par_value=" + Dom.get("gift_card_par_value").value + "&cardExpirationDate=" + Dom.get("cardExpirationDate").value
            );
        };


        var gift_his_reset = function () {
            var username = Dom.get("username").value;
            YAHOO.util.Connect.asyncRequest(
                'GET',
                '/admin/ozing/gift/reset?username='+ encodeURI(username)+"&time="+new Date().getTime(),
                {
                    success: function (o) {
                        if (o.responseText == "true") {
                            alert("重置赠卡历史成功");
                            window.location.href = "/admin/ozing/user/cards?id=" + Dom.get("id").value;
                        }
                    },
                    failure: function (o) {
                        alert(o.statusText);
                    },
                    scope: this
                }
            );
        };
        var handleAddGiftCardCancel = function() {
            this.cancel();
        };

        // Remove progressively enhanced content class, just before creating the module
        YAHOO.util.Dom.removeClass("dialog_add_gift_card", "yui-pe-content");

        // Instantiate the Dialog
        YAHOO.pingmob.container.dialog1 = new YAHOO.widget.Dialog("dialog_add_gift_card",
            { width : "30em",
                fixedcenter : true,
                visible : false,
                constraintoviewport : true,
                buttons : [ { text:"提交", handler:handleAddGiftCardSubmit, isDefault:true },
                    { text:"取消", handler:handleAddGiftCardCancel } ]
            });

        // Validate the entries in the form to require that both first and last name are entered
        YAHOO.pingmob.container.dialog1.validate = function() {
            var data = this.getData();
            if (data.gift_card_par_value == "" || data.cardExpirationDate == "") {
                alert("请输入赠卡的面额和过期日期");
                return false;
            } else {
                return true;
            }
        };

        // Render the Dialog
        YAHOO.pingmob.container.dialog1.render();

        //button.
        var returnUserListBtn = new YAHOO.widget.Button("returnUserListBtn", { onclick:{ fn:returnUserList } });
        var refreshUserEditBtn = new YAHOO.widget.Button("refreshUserEditBtn", { onclick:{ fn:refreshUserCardsEdit } });
        //var save_user_btn = new YAHOO.widget.Button("save_user_btn", { onclick:{ fn:updateUser } });
        var gift_card_to_user_btn = new YAHOO.widget.Button("gift_card_to_user_btn");
        YAHOO.util.Event.addListener("gift_card_to_user_btn", "click", YAHOO.pingmob.container.dialog1.show, YAHOO.pingmob.container.dialog1, true);

        var gift_his_reset_btn = new YAHOO.widget.Button("gift_his_reset_btn", { onclick:{ fn:gift_his_reset } });

        var getTableDataSourceArray = function(datatable){
            var rs = datatable.getRecordSet(),
                len = rs.getLength(),
                data = [];
            for (var index=0; index < len; index++) {
                data.push(rs.getRecord(index).getData());
            }
            return YAHOO.lang.JSON.stringify(data);
        };

        var cardTypeFormatter = function (elCell, oRecord) {
            if (oRecord.getData('cardType') == 'PAID') {
                elCell.innerHTML = "销售卡";
            } else if (oRecord.getData('cardType') == 'ACTIVITY') {
                elCell.innerHTML = "活动卡";
            } else if (oRecord.getData('cardType') == 'CUSTOMIZE') {
                elCell.innerHTML = "定制卡";
            }else if (oRecord.getData('cardType') == 'GIFT') {
                elCell.innerHTML = "赠送卡";
            }else {
                elCell.innerHTML = "";
            }
        };

        //cards table.
        var myColumnDefs_card = [
            {key:"id", label:"ID", sortable:true},
            {key:"cardId", label:"卡号", sortable:true},
            {key:"cardParValue", label:"卡片面值", sortable:true},
            {key:"cardBalance", label:"余额", sortable:true},
            {key:"lockedBalance", label:"锁定余额", sortable:true},
            {key:"cardActivationDate", label:"激活日期",sortable:true},
            {key:"cardExpirationDate", label:"过期日期",sortable:true},
            {key:"active", label:"激活状态",sortable:true,formatter:function (elCell, oRecord, oColumn, oData) {
                if(oData=="true"){
                    elCell.innerHTML ="已激活";
                }else{
                    elCell.innerHTML = "未激活";
                }
            }},
            {key:"cardType", label:"卡片类型",sortable:true,formatter: cardTypeFormatter},
            {key:"dateAdded", label:"创建时间",sortable:true}
        ];

        var myDataSource_card = new YAHOO.util.DataSource(YAHOO.util.Dom.get("user_cards_table"));
        myDataSource_card.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
        myDataSource_card.responseSchema = {
            fields:[
                {key:"id"},
                {key:"cardId"},
                {key:"cardParValue"},
                {key:"cardBalance"},
                {key:"lockedBalance"},
                {key:"cardActivationDate"},
                {key:"cardExpirationDate"},
                {key:"active"},
                {key:"cardType"},
                {key:"dateAdded"}
            ]
        };

        var myDataTable_cards = new YAHOO.widget.DataTable("user_cards_table_div", myColumnDefs_card, myDataSource_card,
            { sortedBy:{key:"cardId", dir:"asc"},
                MSG_EMPTY:messages["js.no.records.found"]
            }
        );

        //card his table...
        var myPaginator = new YAHOO.widget.Paginator({
            containers:['user_cards_thread_paging'],
            rowsPerPage:10,
            previousPageLinkClass:"yui-pg-previous gc-inbox-prev",
            nextPageLinkClass:"yui-pg-next gc-inbox-next"//,
            //template           : "<strong>{CurrentPageReport}</strong> {PreviousPageLink} {NextPageLink}",
            //pageReportTemplate : "{startIndex}-{endIndex} of {totalRecords}"
        });

        var myTableConfig = {
            paginator:myPaginator,
            MSG_EMPTY:messages["js.no.records.found"],
            dynamicData:true,
            initialLoad:false,
            width:'100%'
        };
        var txFormatter = function (elCell, oRecord) {
            if (oRecord.getData('txType') == 'CONSUMPTION') {
                elCell.innerHTML = "答疑消费";
            } else if (oRecord.getData('txType') == 'REFUND') {
                elCell.innerHTML = "退款";
            } else if (oRecord.getData('txType') == 'CHARGEBACK') {
                elCell.innerHTML = "追加扣费";
            }else if (oRecord.getData('txType') == 'OVERDRAW_CONSUMPTION') {
                elCell.innerHTML = "透支消费";
            }else if (oRecord.getData('txType') == 'OVERDRAW_REPAYMENT') {
                elCell.innerHTML = "透支还款";
            }else if (oRecord.getData('txType') == 'REDEEM') {
                elCell.innerHTML = "充值";
            }else {
                elCell.innerHTML = "";
            }
        };

        var myColumnDefs = [
            {key:"Select", label:"", formatter:"checkbox", className:"table-checkbox"},
            {key:"id", label:"ID", sortable:true},
            {key:"cardId", label:'卡号'},
            {key:"txType", label:'交易类型',sortable:true, formatter:txFormatter},
            {key:"txTime", label:'交易时间', sortable:true},
            {key:"costPoint", label:'消费星币'},
            {key:"productId", label:'问题编号',sortable:false},
            {key:"productDesc", label:'问题描述',sortable:false},
            {key:"totalPoint", label:'消费时用户星币余额'}//,
/*
            {key:"orderStatus", label:'交易状态',sortable:false, formatter:function (elCell, oRecord, oColumn, oData) {
                if(oData=="OrderStatusType_NEW"){
                    elCell.innerHTML ="新建";
                }else if(oData=="OrderStatusType_CONFIRM"){
                    elCell.innerHTML = "确认";
                }else if(oData=="OrderStatusType_CANCEL"){
                    elCell.innerHTML = "取消";
                }
            }}
*/
        ];
        var cardHisDataSource = new YAHOO.util.DataSource('/ozing/user/cards/his/json?username='+encodeURI(Dom.get("username").value)  );
        cardHisDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        cardHisDataSource.responseSchema = {
            resultsList:'records',
            metaFields:{
                totalRecords:'totalRecords',
                paginationRecordOffset:"startIndex",
                paginationRowsPerPage:"pageSize",
                sortKey: "sort",
                sortDir: "dir"
            }
        };
        var cardHisDataTable = new YAHOO.widget.DataTable("user_cards_thread", myColumnDefs, cardHisDataSource, myTableConfig);

        // Show loading message while page is being rendered
        cardHisDataTable.showTableMessage(cardHisDataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);

        // Add the instances to the YAHOO.example namespace for inspection
        YAHOO.pingmob.BHMIntegration_files = {
            myPaginator  : myPaginator,
            usersDataSource : cardHisDataSource,
            usersDataTable  : cardHisDataTable
        };

        // Integrate with Browser History Manager
        var History = YAHOO.util.History;

        // Define a custom function to route sorting through the Browser History Manager
        var handleSorting = function (oColumn) {
            // Calculate next sort direction for given Column
            var sDir = this.getColumnSortDir(oColumn);

            // The next state will reflect the new sort values
            // while preserving existing pagination rows-per-page
            // As a best practice, a new sort will reset to page 0
            var newState = generateRequest(0, oColumn.key, sDir, this.get("paginator").getRowsPerPage());

            // Pass the state along to the Browser History Manager
            History.navigate("cardHisTable", newState);
        };
        cardHisDataTable.sortColumn = handleSorting;

        // Define a custom function to route pagination through the Browser History Manager
        var handlePagination = function (state) {
            // The next state will reflect the new pagination values
            // while preserving existing sort values
            // Note that the sort direction needs to be converted from DataTable format to server value
            var sortedBy  = this.get("sortedBy"),
                newState = generateRequest(
                    state.recordOffset, sortedBy.key, sortedBy.dir, state.rowsPerPage
                );

            // Pass the state along to the Browser History Manager
            History.navigate("cardHisTable", newState);
        };

        // First we must unhook the built-in mechanism...
        myPaginator.unsubscribe("changeRequest", cardHisDataTable.onPaginatorChangeRequest);
        // ...then we hook up our custom function
        myPaginator.subscribe("changeRequest", handlePagination, cardHisDataTable, true);

        // Update totalRecords on the fly with values from server
        cardHisDataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
            var meta = oResponse.meta;
            oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
            oPayload.pagination = {
                rowsPerPage:meta.paginationRowsPerPage || 10,
                recordOffset:meta.paginationRecordOffset || 0
            };
            if(oPayload.totalRecords==undefined){
                oPayload.totalRecords=0;
            }
            oPayload.sortedBy = {
                key: meta.sortKey || "txTime",
                dir: (meta.sortDir) ? "yui-dt-" + meta.sortDir : "yui-dt-asc" // Convert from server value to DataTable format
            };
            return true;
        };

        var generateRequest = function (startIndex,sortKey,dir,results) {
            var cardId = encodeURIComponent(Dom.get("cards_selector").value);
            startIndex = startIndex || 0;
            sortKey   = sortKey || "txTime";
            dir   = (dir) ? dir.substring(7) : "desc";  //Converts from DataTable format "yui-dt-[dir]" to server value "[dir]"
            results   = results || 10;
            return  "&sort=" + sortKey + "&dir=" + dir +
                "&start_index=" + startIndex + "&num_per_page=" + results  + "&cardId=" + cardId  + "&time=" + new Date().getTime();
        };

        // Called by Browser History Manager to trigger a new state
        var handleHistoryNavigation = function (request) {
            //show the "loading" message.
            cardHisDataTable.getTbodyEl().style.display = "none";
            cardHisDataTable.showTableMessage(messages["js.loading"]);

            // Sends a new request to the DataSource
            cardHisDataSource.sendRequest(request, {
                success:function () {
                    //checkUsersAll_btn.set("checked", false); //uncheck all.
                    cardHisDataTable.getTbodyEl().style.display = "";
                    cardHisDataTable.hideTableMessage();
                    cardHisDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                failure:function () {
                    //checkUsersAll_btn.set("checked", false); //uncheck all.
                    cardHisDataTable.getTbodyEl().style.display = "";
                    cardHisDataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                    cardHisDataTable.onDataReturnSetRows.apply(this, arguments);
                },
                scope:cardHisDataTable,
                argument:{} // Pass in container for population at runtime via doBeforeLoadData
            });
        };

        // Calculate the first request
        var initialRequest = History.getBookmarkedState("cardHisTable") || // Passed in via URL
            generateRequest(); // Get default values

        // Register the module
        History.register("cardHisTable", initialRequest, handleHistoryNavigation);

        // Render the first view
        History.onReady(function () {
            // Current state after BHM is initialized is the source of truth for what state to render
            var currentState = History.getCurrentState("cardHisTable");
            handleHistoryNavigation(currentState);
        });

        var renderPage = function () {
            var currentState = History.getCurrentState("cardHisTable") || generateRequest();
            handleHistoryNavigation(currentState);
        };

        var filterCardHis = function () {
            var currentState =  generateRequest();
            handleHistoryNavigation(currentState);
        };

        // Initialize the Browser History Manager.
        YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

        Event.addListener("cards_selector", "change", filterCardHis);


        // free order
        var number_per_page_default = 5;
        var orderPaginator = new YAHOO.widget.Paginator({
            containers: ['txs-thread-paging', 'txs-thread-paging_top'],
            rowsPerPage: number_per_page_default,
            previousPageLinkClass: "yui-pg-previous gc-inbox-prev",
            nextPageLinkClass: "yui-pg-next gc-inbox-next"//,
            //template           : "<strong>{CurrentPageReport}</strong> {PreviousPageLink} {NextPageLink}",
            //pageReportTemplate : "{startIndex}-{endIndex} of {totalRecords}"
        });

        var orderColumnDefs = [
            {key: "orderId", label: "交易号", sortable: false},
            {key: "productId", label: "问题号", sortable: false},
            {key: "dateAdded", label: '消费时间', sortable: true},
            {key: "orderStatus", label: '当前状态', sortable: false, formatter:function (elCell, oRecord) {
                if (oRecord.getData('orderStatus') == 'OrderStatusType_CONFIRM') {
                    elCell.innerHTML = "已确认";
                } else if (oRecord.getData('orderStatus') == 'OrderStatusType_CANCEL') {
                    elCell.innerHTML = "已取消";
                } else if (oRecord.getData('orderStatus') == 'OrderStatusType_NEW') {
                    elCell.innerHTML = "新建";
                } else {
                    elCell.innerHTML = "其它";
                }
            }},
            {key: "orderType", label: '问题类型', sortable: false, formatter:function (elCell, oRecord) {
                if (oRecord.getData('orderType') == 'OFFLINEQA') {
                    elCell.innerHTML = "离线答疑";
                } else if (oRecord.getData('orderType') == 'ONLINEQA') {
                    elCell.innerHTML = "在线答疑";
                } else {
                    elCell.innerHTML = "其它";
                }
            }},
            {key:"productDesc", label:'消费描述',sortable:false}
        ];

        var txsDataSource = new YAHOO.util.DataSource('/ozing/freeOrder/json?');
        txsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        txsDataSource.responseSchema = {
            resultsList:'records',
            metaFields:{
                totalRecords: 'totalRecords',
                paginationRecordOffset: "startIndex",
                paginationRowsPerPage: "pageSize",
                sortKey: "sort",
                sortDir: "dir"
            }
        };

        var orderGenerateRequest = function (oState, oSelf) {
            var username = encodeURIComponent(Dom.get("username").value);
            var deviceNumber = '';
            var startDate = '';;
            var endDate = '';;

            oState = oState || { pagination: null, sortedBy: null };
            var sort = (oState.sortedBy) ? oState.sortedBy.key : "dateAdded";
            var dir = (oState.sortedBy && oState.sortedBy.dir === YAHOO.widget.DataTable.CLASS_DESC) ? "desc" : "asc";
            var startIndex = (oState.pagination) ? oState.pagination.recordOffset : 0;
            var results = (oState.pagination) ? oState.pagination.rowsPerPage : number_per_page_default;

            return  "sort=" + sort + "&dir=" + dir + "&start_index=" + startIndex + "&num_per_page=" +
                results + "&username=" + username + "&deviceNumber=" + deviceNumber +
                "&startDate=" + startDate + "&endDate=" + endDate + "&date=" + new Date().getTime();
        };

        var orderTableConfig = {
            paginator: orderPaginator,
            generateRequest: orderGenerateRequest,
            initialRequest: orderGenerateRequest(),
            MSG_EMPTY: messages["js.no.records.found"],
            dynamicData: true,
            initialLoad: true,
            width: '100%'
        };

        var txsDataTable = new YAHOO.widget.DataTable("txs-thread-list", orderColumnDefs, txsDataSource, orderTableConfig);

        // Show loading message while page is being rendered
        txsDataTable.showTableMessage(txsDataTable.get("MSG_LOADING"),YAHOO.widget.DataTable.CLASS_LOADING);

        txsDataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
            var meta = oResponse.meta;
            oPayload.totalRecords = meta.totalRecords || oPayload.
                totalRecords
            ;
            oPayload.pagination = { rowsPerPage:meta.paginationRowsPerPage ||
                number_per_page_default,
                recordOffset:meta.paginationRecordOffset || 0
            };
            if(oPayload.totalRecords==undefined){
                oPayload.totalRecords=0;
            }
            oPayload.sortedBy = {
                key: meta.sortKey || "dateAdded",
                dir: (meta.sortDir) ? "yui-dt-" + meta.
                    sortDir : "yui-dt-asc"
            };
            return true;
        };

        // Add the instances to the YAHOO.example namespace for inspection
        YAHOO.pingmob.BHMIntegration_files
            ={
            orderPaginator  :orderPaginator,
            txsDataSource : txsDataSource,
            txsDataTable  : txsDataTable
        };

        return {
            oDS_cards:myDataSource_card,
            oDT_cards:myDataTable_cards,
            oDS_orders:txsDataSource,
            oDT_orders:txsDataTable,
            oDS_his:cardHisDataSource,
            oDT_his:cardHisDataTable
        };

    }();
});